package com.cg.train.controller;

import com.cg.system.entity.PageBean;
import com.cg.system.entity.Result;
import com.cg.system.handler.WebSocketHandler;
import com.cg.train.entity.Train;
import com.cg.train.service.TrainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@RestController
@RequestMapping("/train")
public class TrainController {
    private static final Logger logger = LoggerFactory.getLogger(TrainController.class);
    
    @Autowired
    private TrainService trainService;
    @Autowired
    private WebSocketHandler webSocketHandler;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/add")
    public Result add(@RequestBody Train train) {
        trainService.add(train);
        System.out.println("数据已添加到数据库");
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    webSocketHandler.sendMessage("审核完成");
                    train.setReviewStatus(0);//改变审核状态
                    trainService.update(train);
                    System.out.println("消息已发送");
                } catch (Exception e) {
                    System.out.println("任务执行失败");
                    e.printStackTrace();
                }
            }
        }, 60 * 1000* 2);

        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody Train train){
        trainService.update(train);
        return Result.success();
    }
    @PostMapping("/delete")
    public Result delete(Integer id){
        trainService.delete(id);
        return Result.success();
    }
   @GetMapping("/list")
    public Result<PageBean<Train>>list(
            Integer pageNum, Integer pageSize,
            @RequestParam(required = false)  String projectCode, @RequestParam(required = false) String trainingProject){
   PageBean<Train>pb= trainService.list(pageNum,pageSize,projectCode,trainingProject);
   return Result.success(pb);
    }
    @GetMapping("/detail")
    public Result<Train> detail(Integer projectId) {
        // 定义缓存key
        String cacheKey = "train:detail:" + projectId;
        // 从缓存中获取数据
        Train cachedTrain = (Train) redisTemplate.opsForValue().get(cacheKey);
        // 如果缓存中有数据，直接返回
        if (cachedTrain != null) {
            logger.info("缓存命中：projectId={}", projectId);
            return Result.success(cachedTrain);
        }
        logger.info("缓存未命中，从数据库获取：projectId={}", projectId);
        // 缓存中没有，从数据库获取
        Train train = trainService.detail(projectId);
        // 将数据存入缓存，设置过期时间为1小时
        if (train != null) {
            logger.info("数据存入缓存：projectId={}", projectId);
            redisTemplate.opsForValue().set(cacheKey, train, 1, TimeUnit.HOURS);
        }
        return Result.success(train);
    }
}
